# -*- coding: utf-8 -*-
"""
admin loign controller
admin logout controller
"""
from framework.admincontroller import AdminController
from framework.controller import Controller
from framework.session import Session
import json
import hashlib
from models.admin import AdminModel
import tornado.web
from framework.redi import RedisModel

class LoginCtrl(Controller):
    """
    login controller
    """

    _redir = None

    # Entry points
    def initialize(self):
        """check login status"""
        uthor = self.get_secure_cookie('userthor')
        athor = self.get_secure_cookie('thor')
        if uthor or athor:
            if athor:
                sess = Session(athor)
            else:
                sess = Session(uthor)
            if sess['type'] == 0:
                self._redir = '/user'
            elif sess['type'] == 1:
                self._redir = '/'
            else:
                self._redir = None

    def get(self):
        """login ui"""
        if self._redir:
            self.redirect(self._redir)
            return
        next_url = self.get_argument('next', '/')
        self.render("login/login.html", n=next_url)

    def post(self):
        """login handler"""
        r_msg = dict(err=0)
        # r_msg = {"err": 0, "href": "/"}
        r_msg['href'] = self.get_argument('next', '/')
        # logined
        if self.current_user:
            self.ajax_out(**r_msg)
            return
        # get quest args
        user_name = self.get_argument('user_name').strip()
        user_pass = self.get_argument('user_pass').strip()
        remember = int(self.get_argument("remember"))
        if len(user_name) < 4 or len(user_pass) < 6:
            # where not allow
            r_msg['err'] = 1
            r_msg['msg'] = u'用户输入不符合标准'
            self.ajax_out(**r_msg)
            return
        # admin login check
        user = AdminModel().find_one({'name': self.get_argument('user_name')})
        if not user:
            # not admin find
            r_msg['err'] = 1
            r_msg['msg'] = u'用户不存在'
            self.ajax_out(**r_msg)
            return
        # admin find check the pass
        pw = hashlib.md5()
        pw.update(user_pass)
        if pw.hexdigest() != user.get('pass'):
            # admin pass not match
            r_msg['err'] = 1
            r_msg['msg'] = u'密码与用户不符'
            self.ajax_out(**r_msg)
            return
        # admin type
        if not user.get('type'):
            r_msg['err'] = 1
            r_msg['msg'] = u'用户没有操作权限'
            self.ajax_out(**r_msg)
            return
        # admin set
        if remember:
            salt = self.request.remote_ip + self.request.headers['User-Agent']
            md5 = hashlib.md5()
            md5.update(salt + user.get('pass') + user.get("name"))
            token = md5.hexdigest()
            self.set_secure_cookie("tracknick", user.get("name"))
            self.set_secure_cookie("token", token)
        # self.current_user = tornado.web.RequestHandler.current_user = user
        self.current_user = user
        thor = self.get_secure_cookie("thor")
        sess = Session(thor)
        sess.set_hmset(user)
        self.ajax_out(**r_msg)

class LogoutCtrl(AdminController):
    """logout"""
    @tornado.web.authenticated
    def get(self):
        """logout handler"""
        # self.current_user = tornado.web.RequestHandler.current_user = None
        self.current_user = None
        thor = self.get_secure_cookie("thor")
        sess = Session(thor)
        sess.clear_all()
        # clear cookies
        self.clear_cookie("thor")
        self.clear_cookie("tracknick")
        self.clear_cookie("token")
        # loaction to url
        msg = dict(err=0, href='/')
        self.ajax_out(**msg)
